package com.springstudy.redisSpring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;

/**
 * spring项目中利用配置文件使用redis
 *
 * @author chenrongrong
 * @since 2020/4/7 9:30
 */
public class TemplateMain {
    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
        RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);
        //基本操作
        redisTemplate.opsForValue().set("key2", "value2");
//        redisTemplate.opsForValue().set("key1", "value1");
//        String test = redisTemplate.opsForValue().get("key1").toString();
        //对某一键值连续操作
//        BoundValueOperations ops = redisTemplate.boundValueOps("key1");
//        ops.set("val2");
//        String test = ops.get().toString();
//        System.out.println(test);
//        redisTemplate.opsForHash().put("hash", "field", "hvalue");

        //使用sessionCallback，只需要打开一次连接
        //useSessionCallback(redisTemplate);
    }

    //使用redisCallback执行redis，只需开启一次连接
    public static void useRedisCallback(RedisTemplate redisTemplate) {
        redisTemplate.execute((RedisCallback) redisConnection -> {
            redisConnection.set("key1".getBytes(), "value1".getBytes());
            redisConnection.hSet("hash".getBytes(), "field".getBytes(), "hvalue".getBytes());
            return null;
        });
    }

    //使用redisCallback执行redis，只需开启一次连接，比起redisCallback操作更友好，一般情况优先使用
    public static void useSessionCallback(RedisTemplate redisTemplate) {
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {
                redisOperations.opsForValue().set("key1", "value1");
                redisOperations.opsForHash().put("hash", "field", "hvalue");
                String test = redisOperations.opsForValue().get("key1").toString();
                System.out.println(test);
                return null;
            }
        });
    }
}
